package cn.jtcoding.common.framework.utils;

import lombok.extern.slf4j.Slf4j;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @description: 日期转换工具类
 * @author: jason.tang
 * @create: 2019/12/23 09:59
 */

@Slf4j
public class DateUtils {

    public static Date localDateToDate(LocalDate localDate) {
        if (localDate == null) {
            return null;
        }
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDate dateToLocalDate(Date date) {
        if (date == null) {
            return null;
        }
        return DateUtils.dateToLocalDateTime(date).toLocalDate();
    }

    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDateTime dateToLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zoneId);
    }

    public static LocalDate addDaysFrom1900(Long days) {
        Calendar calendar = new GregorianCalendar(1900, 0, -1);
        Date date = calendar.getTime();
        LocalDate localDate = DateUtils.dateToLocalDate(date);
        return localDate.plusDays(days);
    }
}
